package alipay

import (
	"context"
	"gitee.com/fangy1111/shop/order"
	"github.com/gin-gonic/gin"
	"github.com/smartwalle/alipay/v3"
	"go.uber.org/zap"
	"net/http"
	"order_bff/global"
	"strconv"
)

func GenerateAlipayUrl(c *gin.Context) {

	orderSn := c.PostForm("order_sn")
	if len(orderSn) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "订单编号不能为空",
			"data": nil,
		})
		return
	}
	var client, err = alipay.New(global.ServerConfig.AlipayConfig.AppId, global.ServerConfig.AlipayConfig.PrivateKey, false)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "支付宝实例化失败",
			"data": nil,
		})
		return
	}

	//查询订单详细信息
	detail, err := global.OrderSrvConn.OrderDetail(context.Background(), &order.OrderRequest{
		OrderSn: orderSn,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "获取订单失败",
			"data": nil,
		})
		return
	}

	orderPricefloat := strconv.FormatFloat(float64(detail.OrderInfo.Total), 'f', 2, 64)

	var p = alipay.TradeWapPay{}
	p.NotifyURL = "http://54ffd2ea.r26.cpolar.top/o/v1/alipay/notify" //异步回调地址
	p.ReturnURL = "http://192.168.137.129:50004/o/v1/alipay/return"   //同步回调地址
	p.Subject = "生鲜订单" + detail.OrderInfo.OrderSn                     //订单标题
	p.OutTradeNo = detail.OrderInfo.OrderSn                           //订单编号
	p.TotalAmount = orderPricefloat                                   //订单金额
	p.ProductCode = "QUICK_WAP_WAY"                                   //拉起支付方式

	url, err := client.TradeWapPay(p)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "拉起支付失败",
			"data": nil,
		})
		return
	}

	// 这个 payURL 即是用于打开支付宝支付页面的 URL，可将输出的内容复制，到浏览器中访问该 URL 即可打开支付页面。
	var payURL = url.String()
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "生成支付连接成功",
		"data": map[string]interface{}{
			"payUrl": payURL,
		},
	})
}

// 支付宝同步回调
func ReturnUrl(c *gin.Context) {
	orderSn := c.Query("out_trade_no")
	if len(orderSn) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "订单编号不能为空",
			"data": nil,
		})
		return
	}
	//查询订单详细信息
	detail, err := global.OrderSrvConn.OrderDetail(context.Background(), &order.OrderRequest{
		OrderSn: orderSn,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "获取订单失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "获取订单成功",
		"data": detail,
	})
}

type AlipayReturn struct {
	TradeNo     string `json:"trade_no"`
	OutTradeNo  string `json:"out_trade_no"`
	TradeStatus string `json:"trade_status"`
}

func NotifyUrl(c *gin.Context) {

	tradeNo := c.PostForm("trade_no")         //支付宝流水号
	outTradeNo := c.PostForm("out_trade_no")  //订单号
	tradeStatus := c.PostForm("trade_status") //支付状态
	//key := "alipay" + outTradeNo
	//
	//alipayReturn := AlipayReturn{
	//	TradeNo:     tradeNo,
	//	OutTradeNo:  outTradeNo,
	//	TradeStatus: tradeStatus,
	//}
	//marshal, _ := json.Marshal(alipayReturn)
	//
	//err := global.RedisClient.LPush(context.Background(), key, marshal).Err()
	//if err != nil {
	//	zap.S().Error("存储redis失败")
	//}
	if tradeStatus == "TRADE_SUCCESS" {
		_, err := global.OrderSrvConn.UpdateOrder(context.Background(), &order.UpdateOrderInfo{
			PayType: "1",
			Status:  "2",
			TradeNo: tradeNo,
			OrderSn: outTradeNo,
		})
		if err != nil {
			zap.S().Error("订单状态更新失败")
			return
		} else {
			// 如果通知消息没有问题，我们需要确认收到通知消息，不然支付宝后续会继续推送相同的消息
			c.String(200, "success")
		}
	}
}
